<template>
  <div class="lazyTree h100">
    <div class="edit-tree-toolbar">
      <div>{{ title }}</div>
    </div>
    <div class="edit-tree-content">
      <el-tree
        class="filter-tree"
        highlight-current
        node-key="id"
        :data="data"
        :props="treeProps"
        :show-checkbox="showCheckbox"
        lazy
        :load="loadNode"
        @check="handleCheckChange"
        @node-click="handleNodeClick"
        @node-expand="keepExpandedNode"
        :default-checked-keys="defaultCheckedNodes"
        :default-expanded-keys="defaultExpandedNodes"
        ref="tree"
      ></el-tree>
    </div>
  </div>
</template>
<script>
import {
  lazyClassifyTree, //获取设备台账树
  searchByNameApi, //根据设备名称模糊查询
  getParentIdsApi //获取某个节点的所有父节点
} from "@/api/equipmentLedger/equipmentManage";
export default {
  props: ["haveRemark"],

  data() {
    return {
      indent: 16,
      title: "组织选择",
      resolve: null,
      btnArr: [],
      showCheckbox: false,
      expandedNodes: [],
      parentIds: [],//父节点集合
      defaultCheckedNodes: [],//默认选中节点
      defaultExpandedNodes: [],//默认展开的节点
      meaningExpandedNum: 0,
      currentNode: {}, //当前节点
      show: false,
      remarkItem: {
        label: "备注",
        prop: "remark",
        type: "text",
        span: 24
      },
      treeProps: {
        label: "label",
        children: [],
        isLeaf: "isLeaf"
      },
      data: []
    };
  },
  created() {
    this.init();
  },
  watch: {},
  methods: {
    currentChange(data, node) {},
    init() {},
    //======================
    //点击事件
    handleNodeClick(node, resolve) {
      this.currentNode = JSON.parse(JSON.stringify(node));
      this.$emit("handleClickTree", node);
    },
    //刷新懒加载的数据
    refreshLoad() {
      this.loadNode.forEach(item => {
        this.loadChildren(item.node, {}, item.resolve);
      });
    },
    //异步树叶子节点懒加载逻辑
    loadNode(node, resolve) {
      this.resolve = resolve;
      if (node.level === 0) {
        //一级节点处理
        this.requestTree(resolve);
      } else {
        //其余节点处理
        this.getIndex(node.data.id, resolve);
        // this.$emit("handleClickTree", node.data);
      }
    },
    //首次加载一级节点
    requestTree(resolve) {
      /* 默认回填展开代码--开始 */
      ///如果需要多次回填，该初始化必需
      this.meaningExpandedNum = 0;
      //默认选中的节点,选中一个节点的时候
      this.defaultCheckedNodes = [
        { id: "E07385630AC547D7985B04BB432EE999", name: "xyz系统121" }
      ];
      let { id } = this.defaultCheckedNodes[0];
      //获取默认选中的节点的父节点
      this.getParentId(id);
      this.parentIds.push(id);
      /*  回填展开节点（这里我略去了从后端拿数据回填到this.expandedNodes里的代码。
          实际上这里如果能直接拿数据放到defaultExpandedNodes里也行） */
      this.defaultExpandedNodes = this.cloneObj(this.expandedNodes);
      /* 默认回填展开代码--结束 */

      lazyClassifyTree("").then(res => {
        let data = res.data;
        //对数据进行处理
        this.setTreeData(data, resolve);
        setTimeout(() => {
          let node = {};
          if (data.length) {
            let dataArr = this.$utils.convert_tree_data(data);
            let obj = dataArr.find(i => i.id == this.currentNode.id); //查找当前选择的节点所在的位置
            node = obj ? this.currentNode : data[0]; //如果已有选中的节点，则显示已选择的节点，没有则默认显示第一个节点
            if (!obj) {
              //如果没有默认选中节点
              this.$refs.tree.setCurrentKey(node.id); //设置当前选择的节点
              this.handleNodeClick(node);
            } else {
              //一个个回填
              let checkNode={}
              for(let i in dataArr){
                if(dataArr[i].id == this.parentIds[0]){
                  checkNode = dataArr[i];
                  break;
                }
              }
              this.$refs.tree.setCurrentKey(id); //设置当前选择的节点
              this.handleNodeClick(checkNode);
            }
          }
        }, 0);
      });
    },
    //异步加载叶子节点数据函数
    getIndex(id, resolve) {
      lazyClassifyTree(id).then(res => {
        let data = res.data;
        //对数据进行处理
        this.setTreeData(data, resolve);
      });
    },
    //获取子节点数据函数
    getClickchild(id, resolve) {
      lazyClassifyTree(id).then(res => {
        let data = res.data;
        this.setTreeData(data, resolve);
        //对是否具有叶子节点进行处理
      });
    },
    //对数据进行处理并且设置树数据
    setTreeData(data, resolve) {
      if (resolve) {
        let treeData = [];
        data.map(i => {
          i.label = i.name;
          i.isLeaf = i.hasChildren ? false : true;
          treeData.push(i);
        });
        resolve(treeData);
      }
    },
    getParentId(id) {
      getParentIdsApi(id).then(res => {
        this.parentIds = res.data;
      });
    },
    //---------------------------------------------------------
    //深度复制对象
    cloneObj(obj) {
      let newObj = {};
      if (typeof obj === "object") {
        if (obj instanceof Array) {
          newObj = [];
        }
        for (var key in obj) {
          let val = obj[key];
          newObj[key] = typeof val === "object" ? this.cloneObj(val) : val;
        }
        return newObj;
      } else {
        return obj;
      }
    },
    //带查重的深复制（仅适用于单层数组）
    cloneWithCheck(Arr) {
      let newArr = [];
      if (Arr.length > 0) {
        newArr.push(this.cloneObj(Arr[0]));
        for (let i = 1; i < Arr.length; i++) {
          let newFlag = newArr.every(item => {
            return item.id !== Arr[i].id;
          });
          if (newFlag) {
            newArr.push(this.cloneObj(Arr[i]));
          }
        }
      }
      return newArr;
    },
    //点击多选框->整理已选选项并保存
    handleCheckChange(node, tree) {
      let list = this.cloneObj(tree.checkedNodes); //tree.checkedNodes-未展开过的节点的子节点无法获取到
      list = list.filter(mItem => {
        return this.expandedNodes.every(item => {
          return item.id !== mItem.id;
        });
      });
      this.value = list;
    },
    //保存展开过的节点
    keepExpandedNode(nodeData, node, tree) {
      let newFlag = this.expandedNodes.every(item => {
        return item.id !== nodeData.id;
      });
      if (newFlag && !nodeData.isLeaf) {
        this.expandedNodes.push(this.cloneObj(nodeData));
      }
    }
  }
};
</script>

<style lang="less" scoped>
.lazyTree {
  border: 1px solid #ebeef5;
  min-height: 300px;
  overflow-y: auto;
  overflow-x: auto;
  margin-bottom: 10px;
}

.edit-tree-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
}
</style>